import 'package:flutter/material.dart';
import 'package:flutter_1/utils/db/DatabaseHelper.dart';
import 'package:flutter_1/utils/image_url.dart';
import 'package:flutter_1/utils/language/message.dart';
import 'package:flutter_1/utils/screen_size.dart';
import 'package:flutter_1/utils/style.dart';
import 'package:flutter_1/views/login.dart';
import 'package:flutter_1/views/components/older_btn.dart';
import 'package:flutter_1/views/order_create_page.dart';
import 'package:flutter_1/views/order_detail_page.dart';
import 'package:flutter_1/views/user_create_page.dart';
import 'package:get/get.dart';

/// 订单管理PC
// ignore: must_be_immutable
class OrderManagementPageDesktop extends StatefulWidget {
  String name = "";
  // 0 - 贸易商，1-客户
  int num = 0;
  
  OrderManagementPageDesktop(
      {super.key, required this.name, required this.num});

  @override
  State<OrderManagementPageDesktop> createState() =>
      _OrderManagementPageDesktopState();
}

class _OrderManagementPageDesktopState
    extends State<OrderManagementPageDesktop> {
  int indexpage = 1;

  /// 订单列表(发货状态：1-待处理 2-处理中 3-已发货 4-已送达 5-已取消)
  List orderList = [];
  // 客户代码
  String customerCode = "";

  /// 用户列表
  List userList = [];
  @override
  void initState() {
    super.initState();
    queryOrderList();
  }

  /// 查询用户表
  queryUserList() async {
    List<Map<String, dynamic>> res = await DatabaseHelper.query('User_table');
    userList = []; // 清空当前数据
    setState(() {
      if (res.isNotEmpty) {
        userList = res;
      } else {
        userList = [];
      }
    });
  }

  /// 查询订单表
  queryOrderList() async {
    // 供货商
    if (widget.num == 0) {
      List<Map<String, dynamic>> res =
          await DatabaseHelper.query('Order_table');
      setState(() {
        if (res.isNotEmpty) {
          orderList = res;
        } else {
          orderList = [];
        }
      });
    } else {
      // 用户：先查用户表获取客户代码，用客户代码查订单
      List<Map<String, dynamic>> res = await DatabaseHelper.query('User_table',
          where: 'username = ?', whereArgs: [widget.name]);
      String customerCode = "";
      if (res.isNotEmpty) {
        customerCode = res[0]["customer_code"];
        debugPrint("customerCode --------- $customerCode");
        List<Map<String, dynamic>> data = await DatabaseHelper.query(
            'Order_table',
            where: 'customer_code = ?',
            whereArgs: [customerCode]);
        setState(() {
          if (data.isNotEmpty) {
            orderList = data;
          } else {
            orderList = [];
          }
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Style.c_8cd5ff,
        title: Text(Strem.title,
            style: Style.c_white_size18_bold, textAlign: TextAlign.left),
        leading: null, // 取消左方按钮
        automaticallyImplyLeading: false, // 确保不显示返回按钮
        actions: widget.num == 0
            ? [
                OlderBtn.olderBtn(
                    Icons.assignment,
                    Strem.orderManagement,
                    indexpage == 1 ? Style.c_ffe896 : Style.c_white,
                    Style.c_back87, () {
                  setState(() {
                    indexpage = 1;
                    queryOrderList();
                  });
                }),
                OlderBtn.olderBtn(
                    Icons.manage_accounts,
                    Strem.userList,
                    indexpage == 2 ? Style.c_ffe896 : Style.c_white,
                    Style.c_back87, () {
                  setState(() {
                    indexpage = 2;
                    queryUserList();
                  });
                }),
              ]
            : [],
      ),
      body: SingleChildScrollView(
        child: Container(
            margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 30),
            child: Column(
              children: [
                Row(
                  children: [
                    // 订单管理
                    if (indexpage == 1 && widget.num == 0) ...[
                      OlderBtn.olderBtn(Icons.add, Strem.createANewOrder,
                          Style.c_22c55e, Style.c_white, () {
                        Get.to(OrderCreatePage())!.then((_) {
                          queryOrderList();
                        });
                      })
                    ],
                    // 用户管理
                    if (indexpage == 2 && widget.num == 0) ...[
                      OlderBtn.olderBtn(Icons.add, Strem.createAUser,
                          Style.c_22c55e, Style.c_white, () {
                        Get.to(const UserCreatePage())!.then((_) async {
                          await Future.delayed(
                              Duration(milliseconds: 500)); // 延迟一会再查询
                          queryUserList();
                        });
                      })
                    ],
                    OlderBtn.olderBtn(Icons.exit_to_app, Strem.exit,
                        Style.c_ef4444, Style.c_white, () {
                      Get.offAll(const Login());
                    }),
                  ],
                ),
                ScreenSize.height(15),
                // 表标题
                Container(
                  width: ScreenSize.screenWidth(context) - 20,
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                      color: Style.c_8cd5ff,
                      borderRadius: const BorderRadius.vertical(
                          top: Radius.circular(10))),
                  child: Row(
                    children: [
                      Icon(
                        indexpage == 1
                            ? Icons.assignment
                            : Icons.manage_accounts,
                        color: Style.c_white,
                        size: 20,
                      ),
                      ScreenSize.width(5),
                      Text(
                        indexpage == 1 ? Strem.listOfOrders : Strem.userList,
                        style: Style.c_white_size14_bold,
                      )
                    ],
                  ),
                ),
                // 表内容
                Container(
                  width: ScreenSize.screenWidth(context) - 20,
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                      color: Style.c_white,
                      borderRadius: const BorderRadius.vertical(
                          bottom: Radius.circular(10))),
                  child: indexpage == 1 ? orderTable() : userTable(),
                )
              ],
            )),
      ),
    );
  }

  /// 无数据
  Widget notData() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 30),
      child: Column(
        children: [
          Image.asset(
            ImageUrl.shoppingCar,
            width: 50,
          ),
          Text(
            Strem.unOrder,
            style: Style.c_back54_size18,
          )
        ],
      ),
    );
  }

  /// 横向表格
  Widget rowWidget(String title, String con, bool isOrderCode) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 3),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            title,
            style: Style.c_black_size14,
          ),
          ScreenSize.width(15),
          Flexible(
            child: Text(
              con,
              style:
                  isOrderCode ? Style.c_3b82f6_size14 : Style.c_black87_size14,
            ),
          )
        ],
      ),
    );
  }

  // 状态
  Widget status(String txt) {
    Color txtColor = Colors.black;
    Color bgColor = Colors.black;
    String content = "";
    if (txt == '1') {
      txtColor = Style.c_back87;
      bgColor = Style.c_back12;
      content = Strem.pendingProcessing;
    } else if (txt == '2') {
      txtColor = Style.c_8cd5ff;
      bgColor = Style.c_3b82f6;
      content = Strem.processing;
    } else if (txt == '3') {
      txtColor = Style.c_ffe896;
      bgColor = Style.c_865419;
      content = Strem.Shipped;
    } else if (txt == '4') {
      txtColor = Style.c_22c55e;
      bgColor = Style.c_3e8459;
      content = Strem.Delivered;
    } else if (txt == '5') {
      txtColor = Style.c_fee2e2;
      bgColor = Style.c_aa1f24;
      content = Strem.Cancelled;
    }
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 3),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            Strem.state,
            style: Style.c_black_size14,
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 3),
            decoration: BoxDecoration(
                color: bgColor, borderRadius: BorderRadius.circular(5)),
            child: Text(
              content,
              style: TextStyle(color: txtColor),
            ),
          )
        ],
      ),
    );
  }

  /// 操作按钮
  Widget operateBtn(String txt, Color color, Function fun) {
    return GestureDetector(
      onTap: () {
        fun();
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3),
        decoration:
            BoxDecoration(color: color, borderRadius: BorderRadius.circular(5)),
        child: Text(
          txt,
          style: TextStyle(color: Style.c_white),
        ),
      ),
    );
  }

  /// 订单列表
  Widget orderTable() {
    if (orderList.isEmpty) {
      return notData();
    } else {
      List<Widget> listWidget = [];
      for (int i = 0; i < orderList.length; i++) {
        listWidget.add(Container(
          padding: EdgeInsets.all(10),
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(
                      width: 1,
                      color: i != orderList.length - 1
                          ? Style.c_back12
                          : Colors.transparent))),
          child: Column(
            children: [
              rowWidget(
                  Strem.orderNumber, orderList[i]["order_id"] ?? "", true),
              rowWidget(
                  Strem.productName, orderList[i]["product_name"] ?? "", false),
              rowWidget(
                  Strem.quantity, orderList[i]["quantity"].toString(), false),
              rowWidget(
                  Strem.price, orderList[i]["total_price"].toString(), false),
              status(orderList[i]["status"] ?? "1"),
              rowWidget(
                  Strem.creationtime, orderList[i]["create_time"] ?? "", false),
              rowWidget(Strem.expectedDELIVERYDATE,
                  orderList[i]["expected_delivery_date"] ?? "", false),
              rowWidget(Strem.customerCode, orderList[i]["customer_code"] ?? "",
                  false),
              // 订单详情按钮
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 3),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      Strem.operate,
                      style: Style.c_black_size14,
                    ),
                    operateBtn(Strem.orderDetails, Style.c_3b82f6, () {
                      Get.to(OrderDetailPage(
                        orderData: orderList[i],
                        num: widget.num,
                      ))!
                          .then((_) {
                        print('Returned from OrderDetailPage');
                        queryOrderList();
                      }).catchError((error) {
                        print("Error occurred: $error");
                      });
                    })
                  ],
                ),
              )
            ],
          ),
        ));
      }
      return Column(
        children: listWidget,
      );
    }
  }

  /// 用户列表
  Widget userTable() {
    if (userList.isEmpty) {
      return notData();
    } else {
      List<Widget> listWidget = [];
      for (var i = 0; i < userList.length; i++) {
        listWidget.add(
          Container(
            padding: const EdgeInsets.all(10),
            decoration: BoxDecoration(
                border: Border(
                    bottom: BorderSide(
                        width: 1,
                        color: i != orderList.length - 1
                            ? Style.c_back12
                            : Colors.transparent))),
            child: Column(
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      width: 30,
                      height: 30,
                      alignment: Alignment.center,
                      margin: const EdgeInsets.only(right: 5, bottom: 5),
                      decoration: BoxDecoration(
                          shape: BoxShape.circle, color: Style.c_8cd5ff),
                      child: Text(
                        userList[i]["username"]?[0] ?? '',
                        style: Style.c_white_size14_bold,
                      ),
                    ),
                    Text(
                      userList[i]["name"],
                      style: Style.c_black87_size16_bold,
                    )
                  ],
                ),
                Column(
                  children: [
                    rowWidget(Strem.username, userList[i]["username"], false),
                    rowWidget(Strem.customerCode, userList[i]["customer_code"],
                        false),
                    rowWidget(Strem.name, userList[i]["name"], false),
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 3),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            Strem.operate,
                            style: Style.c_black_size14,
                          ),
                          Column(
                            children: [
                              // 查看订单
                              operateBtn(Strem.viewTheOrder, Style.c_22c55e,
                                  () async{
                                setState(() {
                                  indexpage = 1;
                                  customerCode = userList[i]["customer_code"];
                                });
                                List<Map<String, dynamic>> data = await DatabaseHelper.query(
            'Order_table',
            where: 'customer_code = ?',
            whereArgs: [customerCode]);
        setState(() {
          if (data.isNotEmpty) {
            orderList = data;
          } else {
            orderList = [];
          }
        });
                              }),
                              ScreenSize.height(5),
                              // 删除用户
                              operateBtn(Strem.deleteTheUser, Style.c_ef4444,
                                  () async {
                                await DatabaseHelper.delete('User_table',
                                    'username = ?', [userList[i]["username"]]);
                                queryUserList();
                              }),
                            ],
                          )
                        ],
                      ),
                    )
                  ],
                )
              ],
            ),
          ),
        );
      }
      return Column(
        children: listWidget,
      );
    }
  }
}
